package cc.picc.quota;

import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;

import org.apache.commons.lang3.StringUtils;

import lombok.NonNull;

/**
 * 
 * @author lijinting01
 *
 */
public class StringQuotaBucketContainer implements QuotaBucketContainer<StringQuotaBucket, String> {

	private ConcurrentMap<String, StringQuotaBucket> valueMap = new ConcurrentHashMap<>();

	/**
	 * 初始化只有一个桶的容器
	 * 
	 * @param spec
	 */
	public StringQuotaBucketContainer(QuotaBucketSpec spec) {
		this(Collections.singletonList(spec));
	}

	/**
	 * 初始化桶容器
	 * 
	 * @param specs
	 */
	public StringQuotaBucketContainer(@NonNull Collection<QuotaBucketSpec> specs) {
		for (QuotaBucketSpec spec : specs) {
			final String name = spec.getName();
			final Integer bound = spec.getCapacity();
			if (StringUtils.isBlank(name) || bound == null || bound.intValue() < 1)
				throw new IllegalArgumentException();
			valueMap.putIfAbsent(name, new StringQuotaBucket(bound));
		}
	}

	@Override
	public Optional<StringQuotaBucket> get(String name) {
		return Optional.ofNullable(valueMap.get(name));
	}

	@Override
	public void get(String name, Consumer<StringQuotaBucket> ifPresentConsumer) {
		get(name).ifPresent(ifPresentConsumer);
	}

	@Override
	public Optional<String> popQuota(String name) {
		Optional<StringQuotaBucket> value = get(name);
		if (value.isPresent())
			return value.get().pop();
		return Optional.ofNullable(null);
	}

	@Override
	public void popQuota(String name, Consumer<String> ifPresentConsumer) {
		popQuota(name).ifPresent(ifPresentConsumer);
	}

}
